package com.demo.java.concurrent.thread;

import lombok.extern.slf4j.Slf4j;

/**
 * 两阶段终止: 异步做一些事情，通过interrupted打断终止异步任务
 */
public class TwoPhaseTerminalTest {
    public static void main(String[] args) throws InterruptedException {
        TwoPhase twoPhase = new TwoPhase();
        twoPhase.start();

        Thread.sleep(3500);
        twoPhase.stop();
    }
}
@Slf4j
class TwoPhase {
    private Thread monitor;
    public void start() {
        this.monitor = new Thread(() -> {
            while (true) {
                if (this.monitor.isInterrupted()) {
                    log.info("monitor interrupted");
                    break ;
                }
                try {
                    Thread.sleep(1000);
                    this.doMonitor();
                } catch (InterruptedException e) {
                    log.error("sleep interrupted", e);
                    // 重新标记interrupt, 否则不会结束
                    this.monitor.interrupt();
                }
            }
        }, "monitor-thread");
        this.monitor.start();
    }

    private void doMonitor() {
        log.info("======== do monitor");
    }

    public void stop() {
        monitor.interrupt();
    }
}
